package srg

import (
	"fmt"
	"strings"
	"time"
)

var timeSub = int64(0)

func iniUniqueId() {
	aa, _ := srds.Time(ctx).Result()
	timeSub = time.Now().Unix() - aa.Unix() //+ 1756260000
}

// 获取唯一id
func GetUniqueIdStr() string {

	curTime := time.Now().Unix() - timeSub
	//timeMid = curTime

	aaa := srds.Incr(ctx, fmt.Sprintf("%s%s:%d", srgHead, "UniqueId", curTime)).Val()

	return fmt.Sprintf("%d", curTime*1000000+aaa)
}

// 获取唯一id
func GetUniqueId() int64 {

	curTime := time.Now().Unix() - timeSub
	//timeMid = curTime

	aaa := srds.Incr(ctx, fmt.Sprintf("%s%s:%d", srgHead, "UniqueId", curTime)).Val()

	return curTime*1000000 + aaa
}

// 获取未来唯一id
// futureTime 未来时间 单位秒
func GetFutureUniqueId(futureTime int64) int64 {

	curTime := time.Now().Unix() - timeSub

	if futureTime < curTime {
		futureTime = curTime
	}

	aaa := srds.Incr(ctx, fmt.Sprintf("%s%s:%d", srgHead, "UniqueId", futureTime)).Val()

	return futureTime*1000000 + aaa
}

// 清理数据
func delExUniqueKey() {
	realTime := time.Now().Unix() - timeSub

	keys, _ := srds.Keys(ctx, fmt.Sprintf("%s%s:*", srgHead, "UniqueId")).Result()
	for _, key := range keys {

		aa := strings.Split(key, ":")
		if len(aa) > 2 {
			if aa[2] < fmt.Sprintf("%d", realTime-10) {
				srds.Del(ctx, key)
			}
		}
	}
}
